package com.dbkj.axb_a;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dbkj.axb_relation.AxbRelationService;
import com.dbkj.common.model.AxbA;
import com.dbkj.common.model.AxbRelation;
import com.dbkj.common.utils.RedisUtils;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.ext.interceptor.Restful;
import com.jfinal.json.Json;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.render.JsonRender;
import com.jfinal.upload.UploadFile;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: Max
 * A号码
 * @Date: 2019/10/29 19:07
 */


public class AxbAController extends Controller {

    @Inject
    AxbAService service;
    @Inject
    AxbRelationService axbRelationService;

    /**
     * A号码的分页展示
     */
    @Before(Restful.class)
    public void index(){
        Integer pageNumber = getParaToInt("pageNumber");
        Integer pageSize = getParaToInt("pageSize");
        String telA = getPara("telA");          //A号码
        String aRelation = getPara("aRelation"); // 归属组名
        String gateway = getPara("gateway");    //网关
        String prefixA = getPara("prefixA");    //A号前缀
        String prefixX = getPara("prefixX");    //X号前缀
//        String concurrent = getPara("concurrent");
        String remark = getPara("remark");
        Page<AxbA> page = service.paginate(pageNumber,pageSize,telA,aRelation,gateway,prefixA,prefixX,remark);

        List<AxbA> list = page.getList();
        for(AxbA a:list){
            String tela = a.getTelA();
            Long len = 0L;
            if(PropKit.getBoolean("is_cluster")){
                len = RedisUtils.cluster.llen("tela_"+tela+"_concurrent_list");
            } else {
                len = RedisUtils.jedis.llen("tela_"+tela+"_concurrent_list");
            }
            a.setCurrentA(len);
        }

        renderJson(Ret.ok().set("total",page.getTotalRow()).set("rows", JSON.toJSON(page.getList())));
    }

    @Before(Restful.class)
    public void save(){
        AxbA a = Json.getJson().parse(getRawData(),AxbA.class);
        AxbRelation relation = axbRelationService.getById(a.getRelationId());

//        if(StrKit.notBlank(a.getConcurrent())){
        if(StrKit.notBlank(relation.getTelaConcurrent())){

            if(PropKit.getBoolean("is_cluster")){
                RedisUtils.cluster.del("tela_"+a.getTelA()+"_concurrent_list");
                for(int k = 0; k<Integer.parseInt(relation.getTelaConcurrent()); k++){
                    RedisUtils.cluster.lpush("tela_"+a.getTelA()+"_concurrent_list","1");
                }
            }else {
                RedisUtils.jedis.del("tela_"+a.getTelA()+"_concurrent_list");
                for(int k = 0; k<Integer.parseInt(relation.getTelaConcurrent()); k++){
                    RedisUtils.jedis.lpush("tela_"+a.getTelA()+"_concurrent_list","1");
                }
            }

        }
        a.save();
        renderJson(Ret.ok());
    }

    @Before(Restful.class)
    public void update(){
        Json.getJson().parse(getRawData(),AxbA.class).update();
        renderJson(Ret.ok());
    }

    public void updateBatch(){
        JSONObject json = JSONObject.parseObject(getRawData());
        JSONObject params = json.getJSONObject("params");
        String telA = params.getString("telA");
        String aRelation = params.getString("aRelation");
        String gateway = params.getString("gateway");
        String prefixA = params.getString("prefixA");
        String prefixX = params.getString("prefixX");
        String remark = params.getString("remark");

        String key = json.getString("key");
        String value = json.getString("value");

        service.updateBatch(telA,aRelation,gateway,prefixA,prefixX,remark,key,value);
        renderJson(Ret.ok());
    }

    public void use(){
        JSONObject json = JSONObject.parseObject(getRawData());
        Integer id = json.getInteger("ids");
        Boolean isUse = json.getBoolean("isUse");
        if(isUse){
            Db.update("update axb_a set is_use = 1 where id =?",id);
        } else {
            Db.update("update axb_a set is_use = 0 where id =?",id);
        }
        renderJson(Ret.ok());
    }

    public void current(){
        JSONArray array = JSONArray.parseArray(getRawData());
        for(int i=0;i<array.size();i++){
            JSONObject object = array.getJSONObject(i);
            String telA = object.getString("telA");
            Integer currentAOld = object.getInteger("currentAOld");
            Integer currentA = object.getInteger("currentA");
            if(PropKit.getBoolean("is_cluster")){
                if(currentA < currentAOld){
                    for(int j=0;j<currentAOld-currentA;j++){
                        RedisUtils.cluster.rpop("tela_"+telA+"_concurrent_list");
                    }
                } else if(currentA > currentAOld){
                    for(int j=0;j<currentA-currentAOld;j++){
                        RedisUtils.cluster.lpush("tela_"+telA+"_concurrent_list","1");
                    }
                }
            }else{
                if(currentA < currentAOld){
                    for(int j=0;j<currentAOld-currentA;j++){
                        RedisUtils.jedis.rpop("tela_"+telA+"_concurrent_list");
                    }
                } else if(currentA > currentAOld){
                    for(int j=0;j<currentA-currentAOld;j++){
                        RedisUtils.jedis.lpush("tela_"+telA+"_concurrent_list","1");
                    }
                }
            }
        }
        renderJson(Ret.ok());

    }

    @Before(Restful.class)
    public void delete(){
        Integer id = getParaToInt();
        service.delete(id);
        renderJson(Ret.ok());
    }

    public void deleteBatch(){
        JSONObject object = JSONObject.parseObject(getRawData());
        service.deleteBatch(object.getJSONArray("ids"));
        renderJson(Ret.ok());
    }

    public void importExcel() throws IOException {
        UploadFile file = getFile();
        if(null == file){
            renderError(400);
        }

        File excelFile = file.getFile();
        InputStream inputStream = new FileInputStream(excelFile);
        List<Object> data = EasyExcelFactory.read(inputStream,new Sheet(1,1));
        inputStream.close();
        boolean flag = false;

        ok:
        for(int i=0;i<data.size();i++){
            String str = data.get(i).toString();
            str = str.replaceAll(" ","");
            str = str.replaceAll("null","");
            str = str.replaceAll("\n","").replaceAll("\t","").replaceAll("\r","");
            String[] arr = str.substring(1,str.length()-1).split(",");
            AxbA anumber = new AxbA();
            for(int j=0;j<arr.length;j++){
                if(j==0){
                    anumber.setTelA(arr[0]);
                }else if(j==1){
                    anumber.setPrefixA(arr[1]);
                } else if(j==2){
                    anumber.setPrefixX(arr[2]);
                } else if(j==3){
                    anumber.setGateway(arr[3]);
                } else if(j==4){
                    anumber.setCallCount(arr[4]);
                } else if(j==5){
                    anumber.setConcurrent(arr[5]);
                } else if(j==6){
                    anumber.setFrequency(arr[6]);
                } else if(j==7){
                    anumber.setARelation(arr[7]);
                    Integer id = axbRelationService.getIdByName(arr[7]);
                    if(id ==null){
                        flag = true;
                        break ok;
                    }
                    anumber.setRelationId(id);
                } else if(j==8){
                    anumber.setRemark(arr[8]);
                }
            }
            //在添加之前删除原来的key
            if(StrKit.notBlank(anumber.getConcurrent())){
                if(PropKit.getBoolean("is_cluster")){
                    RedisUtils.cluster.del("tela_"+anumber.getTelA()+"_concurrent_list");
                    for(int k = 0; k<Integer.parseInt(anumber.getConcurrent()); k++){
                        RedisUtils.cluster.lpush("tela_"+anumber.getTelA()+"_concurrent_list","1");
                    }
                }else{
                    RedisUtils.jedis.del("tela_"+anumber.getTelA()+"_concurrent_list");
                    for(int k = 0; k<Integer.parseInt(anumber.getConcurrent()); k++){
                        RedisUtils.jedis.lpush("tela_"+anumber.getTelA()+"_concurrent_list","1");
                    }
                }

            }
            anumber.setIsUse(true);
            anumber.save();
        }

        file.getFile().delete();

        if(flag){
            renderError(422, new JsonRender(Ret.by("code",422).set("msg","填写的数据有问题,请查看群/组/相关配置的数据")));
            return;
        }
        renderJson(Ret.ok());

    }


    public void getExcelModel() throws IOException {

        File filetemp = new File(PropKit.get("file_addr")+"axba.xlsx");
        File fparent = filetemp.getParentFile();
        if(!fparent.exists()){
            fparent.mkdirs();
        }
        OutputStream out = new FileOutputStream(PropKit.get("file_addr")+"axba.xlsx");
        ExcelWriter writer = EasyExcelFactory.getWriter(out);

        Sheet sheet = new Sheet(1,1);
        sheet.setSheetName("A号码导入");

        Map columnWidth = new HashMap();

        columnWidth.put(0, 5000);
        columnWidth.put(1, 5000);
        columnWidth.put(2, 5000);
        columnWidth.put(3, 5000);
        columnWidth.put(4, 5000);
        columnWidth.put(5, 5000);
        columnWidth.put(6, 5000);
        columnWidth.put(7, 5000);
        sheet.setColumnWidthMap(columnWidth);

        sheet.setHead(service.createListStringHead());

        writer.write(new ArrayList<>(),sheet);
        writer.finish();
        out.flush();
        renderFile(new File(PropKit.get("file_addr")+"axba.xlsx"));
    }


    public void getExcelModel2(){

    }

}
